package com.amita.ez.web;

import com.amita.ez.base.Const;
import com.amita.ez.entity.SysMenu;
import com.amita.ez.service.ISysMenuService;
import com.amita.ez.util.ExcelUtils;
import com.amita.ez.vo.MenuVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;


/**
 * auto generated
 * Sun Jun 13 06:47:31 2021
 */
@RestController
@RequestMapping("/api/sysmenu")
public class SysMenuCtrl  extends BaseCtrl {


    @Autowired
    ISysMenuService sysMenuService;

    @Autowired
    Mapper mapper;






    @GetMapping("/menuselect")
    public Object menuselect(){

//        List<SysMenu> menus = objSQLService.select(new SysMenu(), condition);
        List<SysMenu> menus =sysMenuService.list(new LambdaQueryWrapper<SysMenu>().in(SysMenu::getType, 0, 1).orderByAsc(SysMenu::getMenuSort));

        for (SysMenu menu : menus) {
            if(menu.getType() == 0){
                menu.setComponent("Layout");

            }
        }

        return menus;
    }


    @GetMapping("/tree")
    public Object buildMenus(){

//        List<SysMenu> menus = objSQLService.select(new SysMenu(), condition);
        List<SysMenu> menus =sysMenuService.list(new LambdaQueryWrapper<SysMenu>().in(SysMenu::getType, 0, 1).orderByAsc(SysMenu::getMenuSort));

        for (SysMenu menu : menus) {
            if(menu.getType() == 0){
                menu.setComponent("Layout");

            }
        }

        List<MenuVO> menuVOList = menus.stream().map(el -> mapper.map(el, MenuVO.class)).collect(Collectors.toList());
        List<MenuVO> roots = menuVOList.stream().filter(el-> el.getPid() == null).collect(Collectors.toList());
        List<MenuVO> rests = menuVOList.stream().filter(el -> el.getPid() != null).sorted(Comparator.comparing(MenuVO::getMenuSort)).collect(Collectors.toList());

        buildTree(roots, rests);
        return roots;
    }

    private void buildTree(List<MenuVO> roots, List<MenuVO> rests) {

        if(roots.isEmpty() || rests.isEmpty()){
            return ;
        }

        for (MenuVO root : roots) {
            Long oid = root.getOid();
            List<MenuVO> children = rests.stream().filter(el -> el.getPid() == oid).sorted(Comparator.comparing(MenuVO::getMenuSort)).collect(Collectors.toList());
            if(children.size() >0 ){
                root.setAlwaysShow(true);
                root.setChildren(children);
                List<MenuVO> others = rests.stream().filter(el -> el.getPid() != oid).collect(Collectors.toList());
                buildTree(children, others);
            }


        }

    }



    /**
     * queryWrapper
     * @param query
     * @return
     */
    private QueryWrapper<SysMenu> getQueryWrapper(SysMenu query, String sort) {
        QueryWrapper<SysMenu> queryWrapper = new QueryWrapper<>();
//        String deptNo = query.getDeptNo();
//        if(StringUtils.isNotBlank(deptNo)){
//            queryWrapper.eq("dept_no",deptNo);
//        }
//        String deptName = query.getDeptName();
//        if(StringUtils.isNotBlank(deptName)){
//            queryWrapper.like("dept_name", deptName);
//        }

//        queryWrapper.lambda().orderByAsc(SysMenu::getRealclass);
        if(StringUtils.isNotBlank(sort)){
            sort = sort.replace(",asc", "");
            if(sort.endsWith(",desc")){
                queryWrapper.orderByDesc(sort.replace(",desc", ""));
            }else {
                queryWrapper.orderByAsc(sort);
            }
        }
        return queryWrapper;
    }

    /**
     * 查询全部 (最多返回 100条记录)
     * @return
     */
    @GetMapping("/all")
    public Object all(SysMenu query, String sort){
        IPage<SysMenu> pageCondition = new Page(1, 1000);
        QueryWrapper<SysMenu> queryWrapper = getQueryWrapper(query, sort);
        IPage<SysMenu> result = sysMenuService.page(pageCondition, queryWrapper);
        List<SysMenu> records = result.getRecords();

        return records;
    }
    /**
     * 查询 分页
     * @param page
     * @param size
     * @return
     */
    @GetMapping()
    public Object find(@RequestParam(value = "page",defaultValue = "1")int page,
                       @RequestParam(value = "size",defaultValue = "10")int size,

                       SysMenu query,String sort){
        IPage<SysMenu> pageCondition = new Page(page, size);
        QueryWrapper<SysMenu> queryWrapper = getQueryWrapper(query, sort);
        IPage<SysMenu> result = sysMenuService.page(pageCondition, queryWrapper);
        return result;
    }


    /**
     * 查询 详情
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Object findOne(@PathVariable("id") String id){
        SysMenu item = sysMenuService.getById(id);
        return item;
    }

    /**
     * 保存/更新
     * @param sysMenu
     * @return
     */
    @PostMapping()
    public Object saveIt (SysMenu sysMenu){

        boolean flag = sysMenuService.saveOrUpdate(sysMenu);
        Assert.isTrue(flag, Const.CRUD_FAIL_MSG);
        return R.ok("操作成功");
    }

    /**
     * 删除
     * @param ids
     * @return
     */
    @PostMapping("/d")
    public void remove(String ids){
        boolean flag =  sysMenuService.removeByIds(Arrays.asList(ids.split(",")));
        Assert.isTrue(flag, Const.CRUD_FAIL_MSG);

    }


    /**
     * 导入
     * @param file
     * @return
     */
    @PostMapping("/import")
    public void doImport(MultipartFile file){

//        Assert.notNull(file, "id should not null");
//        if(file.isEmpty()){
//            throw new RuntimeException("file is empty");
//        }

    }

    /**
     * 导出
     * @param query
     */
    @GetMapping("/export")
    public void doExport(SysMenu query, String sort, HttpServletResponse response) throws IOException {
        IPage pageCondition = new Page(1, 1000);
        QueryWrapper<SysMenu> queryWrapper = getQueryWrapper(query, sort);
        IPage result = sysMenuService.page(pageCondition, queryWrapper);
        List records = result.getRecords();

        ExcelUtils.exportExcel(records, "SysMenu表", null, SysMenu.class, "SysMenu", response);
    }


}
